package lrscp.lib.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

public class SwtUtils {
    public static void message(final Shell parent, final String title, final String message) {
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                MessageBox msg = new MessageBox(parent);
                msg.setText(title);
                msg.setMessage(message);
                msg.open();
            }
        });
    }

    public static void openShell(Shell shell) {
        Display display = Display.getDefault();
        shell.open();
        shell.layout();
        shell.pack();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    /**
     * 
     * @param shell
     * @param yShift
     *            if yShift > 0, then shell will be above the center, vice versa
     */
    public static void center(Shell shell, int yShift) {
        Rectangle r1 = shell.getDisplay().getBounds();
        Rectangle r2 = shell.getBounds();
        int x = (r1.width - r2.width) / 2;
        int y = (r1.height - r2.height) / 2 - yShift;
        shell.setLocation(x > 0 ? x : 0, y > 0 ? y : 0);
    }

    public static boolean messageOkCancel(Shell shell, String title, String msg) {
        MessageBox mb = new MessageBox(shell, SWT.OK | SWT.CANCEL);
        mb.setText(title);
        mb.setMessage(msg);
        return mb.open() == SWT.OK;
    }

    public static Color getColor(int color) {
        return Display.getCurrent().getSystemColor(color);
    }

    public static Font createFont(String name, int height, int style) {
        return new Font(Display.getDefault(), new FontData(name, height, style));
    }

    public static void copyToClipboard(String content) {
        Clipboard clipboard = new Clipboard(Display.getCurrent());
        Transfer[] transfers = new Transfer[] { TextTransfer.getInstance() };
        clipboard.setContents(new String[] { content }, transfers);
        clipboard.dispose();
    }
}
